package top.went.db.dao;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import top.went.pojo.DeptEntity;

import java.util.List;

/**
 * 部门dao
 */
public interface DeptDao extends CrudRepository<DeptEntity, Long> {

    /**
     * 根据id查询部门
     *
     * @param deptId
     * @return
     */
    @Query(nativeQuery = true, value = "select * from USER_CRM.TB_DEPT where DEPT_ID = ?1 and DEPT_IS_DEL = 0")
    public DeptEntity findOneById(Long deptId);

    /**
     * 根据部门名称查询部门
     *
     * @param deptName
     * @return
     */
    @Query(nativeQuery = true, value = "select * from TB_DEPT where DEPT_NAME = ?1 and DEPT_IS_DEL = 0")
    public DeptEntity findOneByDeptName(String deptName);

    /**
     * 查找所有部门
     *
     * @return
     */
    @Query(nativeQuery = true, value = "select * from TB_DEPT where DEPT_IS_DEL = 0")
    public List<DeptEntity> findAllDept();

    /**
     * 部门管理表格
     * @return
     */
    @Query(nativeQuery = true, value = "SELECT tb_dept.dept_id,tb_dept.dept_name,COUNT(TB_USER.USER_ID) AS num " +
            "from tb_dept LEFT JOIN TB_USER ON tb_dept.dept_id=TB_USER.DEPT_ID " +
            "WHERE tb_dept.dept_is_del=0 and (TB_USER.USER_IS_DIMISSION=0 or TB_USER.USER_IS_DIMISSION is NULL) " +
            "GROUP BY tb_dept.dept_id,tb_dept.dept_name")
    public List<Object[]> findAllToTable();

    @Query(nativeQuery = true, value = "SELECT tb_dept.dept_id,tb_dept.dept_name,COUNT(TB_USER.USER_ID) AS num " +
            "from tb_dept LEFT JOIN TB_USER ON tb_dept.dept_id=TB_USER.DEPT_ID " +
            "WHERE tb_dept.dept_is_del=0 and (TB_USER.USER_IS_DIMISSION=0 or TB_USER.USER_IS_DIMISSION is NULL) " +
            "and DEPT_NAME like ?1 GROUP BY tb_dept.dept_id,tb_dept.dept_name")
    public List<Object[]> findAllByDeptNameLike(String deptName);
}
